mod asset;

use asset::{pal::Pal, shp::Shp, OpenRAAssetPlugin};
use bevy::prelude::*;

fn main() {
    App::build()
        .add_startup_system(set_up.system())
        .add_plugins(DefaultPlugins)
        .add_plugin(OpenRAAssetPlugin)
        // .add_system(spawn_image.system())
        .run();
}
pub struct Test;

fn set_up(mut commands: Commands, assets_server: Res<AssetServer>) {
    let pal: Handle<Pal> = assets_server.load("g_orca.pal");
    let shp: Handle<Shp> = assets_server.load("g_orca.shp");

    commands.spawn_bundle(OrthographicCameraBundle::new_2d());

    commands
        .spawn_bundle(SpriteBundle::default())
        .insert(pal)
        .insert(shp)
        .insert(Test);
}

fn spawn_image(
    pals: Res<Assets<Pal>>,
    mut shps: ResMut<Assets<Shp>>,
    mut textures: ResMut<Assets<Texture>>,
    mut color_materials: ResMut<Assets<ColorMaterial>>,
    mut sprites: Query<(&mut Handle<ColorMaterial>, &Handle<Pal>, &Handle<Shp>), With<Test>>,
) {
    if pals.len() == 0 || shps.len() == 0 {
        return;
    }

    for (mut material, pal_handle, shp_handle) in sprites.iter_mut() {
        let pal = pals.get(pal_handle.clone()).unwrap();
        let shp = shps.get_mut(shp_handle).unwrap();
        println!("shp.current_img: {}", shp.current_img);

        let texture_handle = if shp.is_have_texture(shp.current_img) {
            shp.get_texture(shp.current_img)
        } else {
            shp.set_texture(pal, &mut textures, shp.current_img)
        };
        *material = color_materials.add(texture_handle.unwrap().into());
    }
}
